package com.qqt.csr.common.interceptor.auth;

import cn.hutool.core.util.StrUtil;

import com.qqt.csr.common.acl.aics.AICustomerServiceClient;
import com.qqt.csr.common.acl.auth.AuthServiceClient;
import com.qqt.csr.common.acl.auth.resp.AuthInfoDTO;
import com.qqt.csr.common.enums.AuthorizeSourceEnum;
import com.qqt.csr.common.exception.StatusCode;
import com.qqt.csr.common.session.SessionContextHolder;
import com.qqt.csr.common.utils.HttpRequestHeaderUtil;
import com.qqt.csr.common.utils.ServiceAssert;
import com.qqt.csr.common.vo.req.RequestHeader;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class UserAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private AuthServiceClient authServiceClient;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private AICustomerServiceClient aiCustomerServiceClient;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            SessionContextHolder.setHeaderInfo(HttpRequestHeaderUtil.buildRequestHeader(null));
            return true;
        }

        // 映射到方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Authorize annotation = handlerMethod.getBeanType().getAnnotation(Authorize.class);
        IgnoreAuthorize ignoreUserToken = handlerMethod.getMethodAnnotation(IgnoreAuthorize.class);
        if (annotation == null) {
            annotation = handlerMethod.getMethodAnnotation(Authorize.class);
        }

        if (annotation == null || ignoreUserToken != null) {
            SessionContextHolder.setHeaderInfo(HttpRequestHeaderUtil.buildRequestHeader(null));
            return true;
        }

        // 校验token
        if(AuthorizeSourceEnum.WEB.equals(annotation.source())){
            String token = request.getHeader(RequestHeader.AUTHORIZATION);
            AuthInfoDTO authInfoDto = authServiceClient.getAuthInfoDto(token);
            ServiceAssert.notNull(authInfoDto, StatusCode.Common.NO_TOKEN,"调用授权服务，获取授权信息为空！");
            SessionContextHolder.setHeaderInfo(HttpRequestHeaderUtil.buildRequestHeader(authInfoDto));
            ServiceAssert.isTrue(StringUtils.isNotBlank(SessionContextHolder.getHeaderInfo().getTenantId()), StatusCode.Common.ILLEGAL.getCode(), "无效的租户");
            return true;
        }else if(AuthorizeSourceEnum.H5.equals(annotation.source())){
            SessionContextHolder.setHeaderInfo(HttpRequestHeaderUtil.buildRequestHeader(null));
            String token = SessionContextHolder.getHeaderInfo().getAccessToken();
            String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
            ServiceAssert.isTrue(StringUtils.isNotBlank(tenantId), StatusCode.Common.ILLEGAL.getCode(), "无效的租户");
            ServiceAssert.isTrue(StringUtils.isNotBlank(token), StatusCode.Common.NO_TOKEN.getCode(), "非法访问");
            aiCustomerServiceClient.checkVisitorToken(tenantId, token);
            return true;
        }else{
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
        SessionContextHolder.clear();
    }
}
